package com.cms.bs.util;

import com.cms.bs.config.Config;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import java.util.ArrayList;
import java.util.List;

public class RedisUtil {

    private static ShardedJedisPool shardedJedisPool;

    private static ShardedJedis shardedJedis;

    static {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(50);
        config.setMaxIdle(10);
        config.setMaxWaitMillis(5000);
        config.setTestOnBorrow(false);

        List<JedisShardInfo> list = new ArrayList<JedisShardInfo>();
        JedisShardInfo info = new JedisShardInfo(Config.getPropStr("redis.host"),
                BaseTypeUtil.safeInt(Config.getPropStr("redis.port")));
        list.add(info);

        shardedJedisPool = new ShardedJedisPool(config, list);
    }

    /**
     * @param key
     * @return
     * @Title: put
     * @Description: 写入 redis key-value
     * 成功=> =1；	已存在=> =0
     * @author: jiang
     * @date: 2016年5月5日
     */
    public static long put(String key, String value, int liveSeconds) {
        long result = 0;
        try {
            shardedJedis = shardedJedisPool.getResource();
            /*
			 * =0：已存在 =1：成功
			 */
            result = shardedJedis.setnx(key, value);
            if (result == 1) {
                shardedJedis.expire(key, liveSeconds);
            }
        } catch (Exception e) {
            Log4jUtil.error(RedisUtil.class.getName(), "put redis error.", e);
        } finally {
            shardedJedis.close();
        }
        return result;
    }

    /**
     * @param key
     * @return
     * @Title: get
     * @Description: 获取 redis key-value
     * @author: jiang
     * @date: 2016年5月5日
     */
    public static String get(String key) {
        String result = null;
        try {
            shardedJedis = shardedJedisPool.getResource();
            result = shardedJedis.get(key);
        } catch (Exception e) {
            Log4jUtil.error(RedisUtil.class.getName(), "get redis error.", e);
        } finally {
            shardedJedis.close();
        }
        return result;
    }

    /**
     * @param key
     * @return
     * @Title: remove
     * @Description: 删除 redis key
     * 成功=> >1；	不存在=> =0
     * @author: jiang
     * @date: 2016年5月5日
     */
    public static long remove(String key) {
        long result = 0;
        try {
            shardedJedis = shardedJedisPool.getResource();
			/*
			 * =0：不存在 >0：删除成功
			 */
            result = shardedJedis.del(key);
        } catch (Exception e) {
            Log4jUtil.error(RedisUtil.class.getName(), "remove redis error.", e);
        } finally {
            shardedJedis.close();
        }
        return result;
    }

}